

// 337.打家劫舍III
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int rob(TreeNode* root) {
        // 结合DFS 找每条支路中最大可投的金额数

        //增加记忆法搜索
        unordered_map<TreeNode* ,int> m1;
        unordered_map<TreeNode* ,int> m2;
        //0表示上一个位置没偷, 1表示上一个位置偷了
        function<int(TreeNode* ,int)> dfs = [&](TreeNode* t ,int flag)->int{ 
            if(flag == 1 && m1.count(t)) return m1[t];
            if(flag == 0 && m2.count(t)) return m2[t];
            
            int ret = 0;
            int left1 = 0 ,right1 = 0,left2 = 0, right2 = 0;
            if(t -> left) 
            {
                left1 = dfs(t -> left ,1); 
                left2 = dfs(t -> left ,0);
            }
            if(t -> right) 
            {
                right1 = dfs(t -> right ,1); 
                right2 = dfs(t -> right ,0); 
            }
            if(flag == 1)   
            {
                m1[t] = left2+right2;
                return left2+right2;
            }
            else 
            {
                m2[t] =  max(left1+right1+t->val,left2+right2);
                return max(left1+right1+t->val,left2+right2);
            }
        };

        return max(dfs(root,1),dfs(root,0));
    }
};